<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, useTemplateRef } from 'vue'
import Vditor from 'vditor'

// v-model
const model = defineModel<string>({ default: '' })

// 容器dom
const view = useTemplateRef('view')

// vditor实例
let vditor: Vditor | null = null

// 需要标识内部更新
let isInternalUpdate = false

// 是否渲染完毕
let isRender = ref(false)

onMounted(() => {

    vditor = new Vditor(view.value as HTMLElement, {
        minHeight: 100,
        cache: { enable: false },
        value: model.value,
        after: () => {
            isRender.value = true
        },
        input: (md) => {
            if (model.value === md) return
            isInternalUpdate = true // 标记为内部更新
            model.value = md
        },
        cdn: "http://test.code9.top/cdn/vditor"
    })

    watch(() => model.value, (newContent) => {
        // 只有外部更新标时才触发
        if (!isInternalUpdate) {
            vditor!.setValue(newContent)
        }
        isInternalUpdate = false // 重置标志
    })

})

onUnmounted(() => {
    vditor!.destroy()
})

</script>

<template>
    <div v-show="isRender" ref="view"> </div>
    <div style="font-size: 14px; color:#999" v-show="!isRender">加载中... </div>
</template>